/*
 * Globals.cpp
 *
 *  Created on: 20/06/2014
 *      Author: Vitor
 */

#include "Globals.h"

Lockable<std::map<unsigned int, unsigned int>> Globals::peers = Lockable<
		std::map<unsigned int, unsigned int>>(
		std::map<unsigned int, unsigned int>());
Lockable<std::vector<User>> Globals::user_table = Lockable<std::vector<User>>(
		std::vector<User>());
Lockable<FileTable*> Globals::file_table = Lockable<FileTable*>(
		new FileTable());
Lockable<bool> Globals::active = Lockable<bool>(true);
Lockable<bool> Globals::identified = Lockable<bool>(false);

Lockable<PeerIdentifier> Globals::peer = Lockable<PeerIdentifier>(
		PeerIdentifier());
Lockable<User> Globals::logged_user = Lockable<User>(User("", ""));

ByteQueue Globals::serialize_user_table() {
	ByteQueue serial;

	serial.push<unsigned int>(user_table.get().size());

	for (auto user : user_table.get()) {
		serial.push<std::string>(user.get_name());
		serial.push<std::string>(user.get_password());
	}
	return serial;
}

ByteQueue Globals::serialize_peers() {

	ByteQueue serial;
	serial.push<unsigned int>(peers.get().size());

	for (auto peer : peers.get()) {
		serial.push<unsigned int>(peer.first);
	}
	return serial;

}

std::vector<User> Globals::deserialize_user_table(ByteQueue& serial) {

	unsigned int size;
	std::vector<User> user_table;

	size = serial.pop<unsigned int>();
	for (unsigned int i = 0; i < size; i++) {
		auto user_name = serial.pop<std::string>();
		auto password = serial.pop<std::string>();
		user_table.push_back(
				User(user_name, password));
	}
	return user_table;
}

std::map<unsigned int, unsigned int> Globals::deserialize_peers(
		ByteQueue& serial) {
	unsigned int size;
	std::map<unsigned int, unsigned int> peers;

	size = serial.pop<unsigned int>();
	for (unsigned int i = 0; i < size; i++) {
		peers[serial.pop<unsigned int>()] = SDL_GetTicks();
	}
	return peers;
}
